<template>
  <div style="min-height: 100vh">
    <Toast :formData="formData"></Toast>
    <div class="header"></div>
    <div class="main" v-show="isShow">
      <div class="reg">注册/登录</div>
      <div class="tel">手机号</div>
      <input type="text" class="Ipt" v-model="phone" maxlength="11" placeholder="请输入手机号" />
      <button
        class="next active"
        :disabled="isDisable"
        :style="{background: phone == '' ? '#ddd' : '#2B6CFE' }"
        @click="NextClick"
      >下一步</button>
      <div class="welcome">
        <div class="welcome_words">欢迎登录安全渝中手机客户端</div>
      </div>
      <div class="agreen">
        注册及表示同意并阅读
        <span class="city" @click="jump">《安全渝中隐私条款》</span>
      </div>
    </div>
    <div class="Coded" v-show="Iputshow">
      <div>
        <div class="Code">请输入验证码</div>
        <div class="Code_tel">
          验证码已发送至手机
          <span>{{phone}}</span>
        </div>
      </div>
      <div class="captcha">
        <input
          v-focus
          class="input"
          v-for="(c, index) in ct"
          :key="index"
          type="number"
          v-model="ct[index]"
          ref="input"
          :style="{borderBottomColor: index <= cIndex ? '#333' : ''}"
          @input="e => {onInput(e.target.value, index)}"
          @keydown.delete="e=>{onKeydown(e.target.value, index)}"
          @focus="onFocus"
          :disabled="loading"
          onkeyup="value=value.replace(/[^\d]/g,'')"
        />
      </div>

      <span class="count">{{count}} s</span>
    </div>
    <div class="content_boxfuck" v-if="fuck">
      <div class="content_box_songfuck">
        <div class="fbfuck">新版发布</div>
        <div class="saveggfuck">应急安全管理平台最新版本发布啦,欢迎体验!</div>
        <div class="linefuck"></div>
        <div class="makesurefuck" @click="UPdatas">立即更新</div>
      </div>
    </div>
  </div>
</template>
<script>
import Toast from "../components/toast";
export default {
  data() {
    return {
      isDisable: false,
      show: false,
      active: false,
      phone: "", //电话号码
      userId: "",
      disabled: false,
      isShow: true, //默认显示输入页面
      Iputshow: false, //验证码页面
      leftGo: false,
      count: "300", //秒
      timer: null,
      showTop: false,
      get_yzm_msg: "",
      time: "", //用户登录的时间记录
      formData: {
        showTop: false,
        text: "",
      },
      ct: ["", "", "", ""],
      loading: false,
      fuck: false,
      sort: 0, //app版本是否需要更新的状态变量
      phone_type: null, //判断手机是什么系统,0为ios，1为安卓
      showeditionObj: "",
    };
  },
  created() {
    this.ismobile(1);
  },
  directives: {
    focus: {
      // 指令的定义
      inserted: function (el) {
        el.focus();
      },
    },
  },
  // watch: {
  //   aCodes(newVal) {
  //     this.aCodes = newVal.replace(/[^\d]/g, "");
  //   }
  // },
  components: {
    Toast,
  },
  computed: {
    ctSize() {
      return this.ct.length;
    },
    cIndex() {
      let i = this.ct.findIndex((item) => item === "");
      i = (i + this.ctSize) % this.ctSize;
      return i;
    },
    lastCode() {
      return this.ct[this.ctSize - 1];
    },
  },
  watch: {
    cIndex() {
      this.resetCaret();
    },
  },
  methods: {
    onInput(val, index) {
      val = val.replace(/\s/g, "");
      if (index == this.ctSize - 1) {
        this.ct[this.ctSize - 1] = val[0]; // 最后一个码，只允许输入一个字符。
      } else if (val.length > 1) {
        let i = index;
        for (i = index; i < this.ctSize && i - index < val.length; i++) {
          this.ct[i] = val[i];
        }
        this.resetCaret();
      }
      if (this.ct.join("").length === 4) {
        this.Login();
      }
    },
    // 重置光标位置。
    resetCaret() {
      this.$refs.input[this.ctSize - 1].focus();
    },
    onFocus() {
      // 监听 focus 事件，将光标重定位到“第一个空白符的位置”。
      let index = this.ct.findIndex((item) => item === "");
      index = (index + this.ctSize) % this.ctSize;
      this.$refs.input[index].focus();
    },
    onKeydown(val, index) {
      if (val === "") {
        // 删除上一个input里的值，并对其focus。
        if (index > 0) {
          this.ct[index - 1] = "";
          this.$refs.input[index - 1].focus();
        }
      }
    },
    check() {
      this.active = !this.active;
    },
    NExtGo() {
      this.showTop = false;
    },
    async NextClick() {
      var that = this;
      //下一步
      if (this.active == true) {
        return this.$toast("请勾选用户协议");
      }
      var regMobile = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (this.phone == "") {
        return this.$toast("请输入手机号");
        // this.formData.showTop = true;
        // this.formData.text = '请输入手机号!';
        // return false;
      }
      if (!regMobile.test(this.phone)) {
        return this.$toast("请输入正确的手机号");
      }
      that.isDisable = true;
      setTimeout(() => {
        that.isDisable = false; //点击一次时隔十秒后才能再次点击
      }, 10000);
      try {
        plus.nativeUI.showWaiting("正在加载...");
      } catch (e) {}
      this.getCode();
      that.axios
        .post(
          this.$global_msg.Url.hosted +
            "/getAuthNum?phone=" +
            that.phone
        )
        .then((res) => {
          console.log(res);
          try {
            plus.nativeUI.closeWaiting();
          } catch (e) {}
          if (res.data.code == 100) {
            try {
              plus.nativeUI.closeWaiting();
            } catch (e) {}
            return this.$toast("获取验证码超时");
          } else if (res.data.code == 300) {
            try {
              plus.nativeUI.closeWaiting();
            } catch (e) {}
            // return this.$toast(res.data.message);
            this.formData.showTop = true;
            this.formData.text = res.data.message;
            return false;
          }
          this.leftGo = true;
          this.isShow = false;
          this.Iputshow = true;
        })
        .catch((err) => {
          try {
            plus.nativeUI.closeWaiting();
          } catch (err) {}
           this.$toast("服务器错误,请稍后再试!");
        });
    },
    Login() {
      var that = this;
      that.axios
        .post(
          this.$global_msg.Url.hosted +
            "/loginyz?phone=" +
            that.phone +
            "&authnum=" +
            that.ct.join("")
        )
        .then((res) => {
          console.log(res);
          if (res.data.code == 400) {
            return this.$toast(res.data.message);
          }
          if (res.data.code == 200) {
            localStorage.setItem("newTime", new Date());
            localStorage.setItem("newTime_1", new Date());
            localStorage.setItem("tel", that.phone);
            localStorage.setItem("username", res.data.data.username);
            localStorage.setItem("super", res.data.data.jc);
            localStorage.setItem("phone", res.data.data.phone);
            localStorage.setItem("userId", res.data.data.userid);
            that.$router.replace({
              path: '/'
            });
          } else {
            that.$toast("验证码输入错误!");
          }
        })
        .catch((err) => {
           console.log(err);
           that.$toast("服务器错误,请稍后再试!");
          //  that.$terminal._error(err)
        });
    },
    jump() {
      //跳转到使用条款
      this.$router.push("/terms");
    },
    getCode() {
      //倒计时
      const TIME_COUNT = 299;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.timer = setInterval(() => {
          if (this.count > 1 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.PrevGo();
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },

    PrevGo() {
      var that = this;
      this.leftGo = false;
      this.isShow = true;
      this.Iputshow = false;
      // this.phone = ''
      this.yzm1 = "";
      this.yzm2 = "";
      this.yzm3 = "";
      this.yzm4 = "";
    },
    down_apk() {
      var _this = this;
      var Terminal = {
        // 辨别移动终端类型
        platform: (function () {
          var u = navigator.userAgent,
            app = navigator.appVersion;
          return {
            // android终端或者uc浏览器
            android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1,
            // 是否为iPhone或者QQHD浏览器
            iPhone: u.indexOf("iPhone") > -1,
            // 是否iPad
            iPad: u.indexOf("iPad") > -1,
          };
        })(),
        // 辨别移动终端的语言：zh-cn、en-us、ko-kr、ja-jp...
        language: (
          navigator.browserLanguage || navigator.language
        ).toLowerCase(),
      };

      // 根据不同的终端，跳转到不同的地址
      var theUrl = "";
      if (Terminal.platform.android) {
        // alert("安卓")
        theUrl = _this.showeditionObj.xzgxUrl;
        if (is_mobileWX() || is_mobileQQForAndroid()) {
        } else {
          location.href = theUrl;
        }
      } else if (Terminal.platform.iPhone) {
        theUrl = "https://itunes.apple.com/us/app/998dian-wan-cheng/id?mt=8";
        location.href = theUrl;
      }

      function is_mobileQQForAndroid() {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/\sQQ/i) == "qq" && /iphone/i.test(ua) == false) {
          return true;
        } else {
          return false;
        }
      }

      function is_mobileQQForIPhone() {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/\sQQ/i) == "qq" && /iphone/i.test(ua) == true) {
          return true;
        } else {
          return false;
        }
      }

      function is_mobileWX() {
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
          return true;
        } else {
          return false;
        }
      }
    },
    UPdatas() {
      this.down_apk();
    },
    ismobile(test) {
      var u = navigator.userAgent,
        app = navigator.appVersion;
      if (
        /AppleWebKit.*Mobile/i.test(navigator.userAgent) ||
        /MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(
          navigator.userAgent
        )
      ) {
        if (window.location.href.indexOf("?mobile") < 0) {
          try {
            if (/iPhone|mac|iPod|iPad/i.test(navigator.userAgent)) {
              // return "0";
              this.phone_type = 0;
              // alert("iphone")
            } else {
              // return "1";
              this.phone_type = 1;
              // alert("Android")
            }
          } catch (e) {}
        }
      } else if (u.indexOf("iPad") > -1) {
        // return "0";
        this.phone_type = 0;
        // alert("iphone")
      } else {
        // return "1";
        this.phone_type = 1;
        // alert("Android")
      }
    },
    //更新方法
    UpdateSystem() {
      if (this.sort == 0) {
        this.plusReady_gengxin();
      } else if (this.sort == 1) {
        this.plusReady_gengxin();
      }
    },
    // 更新方法
    plusReady_gengxin() {
      this.runtime_fun();
    },
    runtime_fun() {
      var _this = this;
      setTimeout(() => {
        plus.runtime.getProperty(plus.runtime.appid, function (inf) {
          // 当前版本
          var wgtVersion = inf.version;
          _this.axios
            .get(
              "/showedition",
              {},
              {
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
              }
            )
            .then(function (data) {
              // 如果有新版本，则提示需要更新
              console.log("aaaa");
              console.log(data.data.rows.zdgxNumber);
              console.log(wgtVersion);
              console.log(data.data.rows.zdgxNumber > wgtVersion);
              _this.showeditionObj = data.data.rows;
              if (data.data.rows.xzgxNumber > wgtVersion) {
                _this.fuck = true;
              } else if (data.data.rows.zdgxNumber > wgtVersion) {
                console.log(11111);
                _this.$toast("有新版本可用");
                setTimeout(() => {
                  console.log(2222);
                  _this.downloadWgt(); // 下载wgt方法
                }, 1000);
              } else {
                if (_this.sort == 1) {
                  console.log("已是最新版本！！！");
                } else {
                  return;
                }
              }
            })
            .catch(function (err) {
              // 请求失败处理
             _this.$terminal._error(err)
            });
        });
      }, 500);
    },
    // 下载wgt方法
    downloadWgt() {
      // 更新文件 wgt 文件地址
      var that = this;
      var wgtUrl = that.showeditionObj.zdgxUrl;
      plus.nativeUI.showWaiting("正在更新...");
      plus.downloader
        .createDownload(
          wgtUrl,
          {
            filename: "_doc/update/",
          },
          function (d, status) {
            if (status == 200) {
              console.log("下载wgt成功：" + d.filename);
              that.installWgt(d.filename); // 安装wgt方法
            } else {
              console.log("下载wgt失败！");
              plus.nativeUI.alert("下载wgt失败！");
            }
            plus.nativeUI.closeWaiting();
          }
        )
        .start();
    },
    //安装方法
    installWgt(path) {
      plus.nativeUI.showWaiting("安装wgt文件...");
      plus.runtime.install(
        path,
        {},
        function () {
          plus.nativeUI.closeWaiting();
          console.log("安装wgt文件成功！");
          plus.nativeUI.alert("应用资源更新完成！", function () {
            plus.runtime.restart();
          });
        },
        function (e) {
          plus.nativeUI.closeWaiting();
          console.log("安装wgt文件失败[" + e.code + "]：" + e.message);
          plus.nativeUI.alert("安装wgt文件失败[" + e.code + "]：" + e.message);
        }
      );
    },
    goBack() {
      if (window.plus) {
        plus.runtime.quit();
      }
    },
  },
  mounted() {
    this.UpdateSystem();
    this.resetCaret();
    document.body.style.backgroundColor = "#FFFFFF";
    if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL);
      window.addEventListener("popstate", this.goBack, false);
    }
  },
  destroyed() {
    window.removeEventListener("popstate", this.goBack, false);
  },
};
</script>
<style scoped>
.header {
  height: 2.4rem;
  background: url(../assets/images/home_bg.png) no-repeat;
  background-size: 100% 100%;
}

.welcome_words {
  margin-left: 0.1666rem;
}

.circle {
  /* width: 0.3333rem;
  height: 0.3333rem; */
  width: 0.4rem;
  height: 0.4rem;
}

.Tick {
  margin-right: 0.1333rem;
}

.reg {
  background-color: white;
  padding: 0.2962962962962963rem;
  font-size: 0.5333rem;
}

.tel {
  background-color: white;
  padding: 0.2962962962962963rem;
  font-size: 0.3733rem;
  color: #696464;
}

.Ipt {
  font-size: 0.4rem;
  border-bottom: 0.04rem solid #8f8f94;
  width: 94%;
  margin-left: 0.2667rem;
  padding: 0.4rem 0;
  margin-bottom: 0.2667rem;
}

.next {
  display: block;
  width: 90%;
  height: 1rem;
  /* background: #2B6CFE; */
  background: #ddd;
  color: #ffffff;
  text-align: center;
  line-height: 1rem;
  margin: auto;
  font-size: 0.36rem;
  margin-top: 0.2667rem;
  /* border-radius: 0.2667rem; */
  border-radius: 0.740741rem;
}

.welcome {
  text-align: center;
  font-size: 0.32rem;
  color: #5f5d5c;
  margin-top: 0.2667rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

.agreen {
  font-size: 0.32rem;
  color: #5f5d5c;
  text-align: center;
  margin-top: 0.2rem;
  display: flex;
  justify-content: center;
}

.city {
  display: inline-block;
  font-weight: 600;
  color: #2d6bfe;
}

.Prev {
  height: 0.4267rem;
  margin-left: 0.2667rem;
  padding-top: 0.2667rem;
}

.Code {
  font-size: 0.5333rem;
  margin-left: 0.2667rem;
  margin-top: 0.8rem;
}

.Code_tel {
  font-size: 0.4rem;
  color: #696464;
  margin-left: 0.2667rem;
  margin-top: 0.2667rem;
}

.yzm {
  text-align: center;
  font-size: 0.4rem;
  width: 20%;
  border-bottom: 1px solid #d2cfcf;
  padding-bottom: 0.2667rem;
  margin-top: 0.6667rem;
  margin-left: 0.1333rem;
  margin-bottom: 0.5333rem;
}

.Ipts {
  margin: 0 auto;
}

.count {
  font-size: 0.4rem;
  margin-left: 1rem;
}

.headers {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
}

.hand {
  z-index: 100;
  width: 3.2133rem;
  height: 2.9333rem;
  position: relative;
  margin: auto;
  margin-top: 2.6667rem;
}

.welcome_word {
  position: relative;
  z-index: 1;
  color: white;
  font-size: 0.4rem;
  text-align: center;
  margin-top: 0.5333rem;
}
.captcha {
  display: flex;
  justify-content: space-around;
  margin-top: 0.5333rem;
  align-items: center;
  margin-bottom: 0.2667rem;
}
.input {
  margin-right: 0.2667rem;
  width: 1.2rem;
  line-height: 1rem;
  text-align: center;
  border: none;
  border-bottom: 1px solid #999999;
  font-size: 0.44rem;
  outline: none;
}
input:last-of-type {
  margin-right: 0;
}
input:disabled {
  color: #000;
  background-color: #fff;
}
.msg {
  text-align: center;
}
.content_boxfuck {
  background: rgba(0, 0, 0, 0.8);
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 90;
  display: flex;
}

.content_box_songfuck {
  width: 90%;
  /* height: 4.8267rem; */
  margin: auto;
  z-index: 100000000;
  align-items: center;
  justify-content: center;
  /* margin-bottom:100%; */
  background: white;
  border-radius: 0.37037rem;
  overflow: hidden;
  padding-bottom: 0.37037rem;
}
.fbfuck {
  font-size: 0.481481rem;
  text-align: center;
  margin-top: 0.37037rem;
}

.saveggfuck {
  font-size: 0.407407rem;
  text-align: center;
  margin-top: 0.185185rem;
}

.makesurefuck {
  color: #007aff;
  font-size: 0.444444rem;
  width: 100%;
  text-align: center;
  margin-top: 0.37037rem;
}

.linefuck {
  border-top: 1px solid#E5E5E5;
  margin-top: 0.740741rem;
}
</style>
